import { createPinia, defineStore } from 'pinia';
import { buildFuse } from '../utils/search';
import { movieService } from '../services/movieService';

export const pinia = createPinia();

export const useMovieStore = defineStore('movies', {
  state: () => ({
    movies: [],
    loading: false,
    error: null,
    fuse: null,
    searchHistory: JSON.parse(localStorage.getItem('search_history') || '[]')
  }),
  getters: {
    // 类型筛选已移除，保留其他getter
  },
  actions: {
    async fetch() {
      if (this.loading) return;
      this.loading = true; this.error = null;
      try {
        // 使用真实的后端API获取电影数据
        const response = await movieService.getMovies();
        // 后端返回分页数据，需要提取content数组
        this.movies = response.content || response;
        this.fuse = buildFuse(this.movies);
      } catch (e) {
        this.error = e.message || String(e);
      } finally {
        this.loading = false;
      }
    },
    
    async searchMovies(params = {}) {
      try {
        const movies = await movieService.getMovies(params);
        return movies;
      } catch (error) {
        console.error('搜索电影失败:', error);
        throw error;
      }
    },
    
    async getMovie(id) {
      try {
        const movie = await movieService.getMovie(id);
        return movie;
      } catch (error) {
        console.error('获取电影详情失败:', error);
        throw error;
      }
    },
    
    async getCategories() {
      try {
        const categories = await movieService.getCategories();
        return categories;
      } catch (error) {
        console.error('获取分类列表失败:', error);
        throw error;
      }
    },
    
    async getActiveCategoriesByType(type) {
      try {
        const categories = await movieService.getActiveCategoriesByType(type);
        return categories;
      } catch (error) {
        console.error('获取分类列表失败:', error);
        throw error;
      }
    },
    
    getById(id) {
      return this.movies.find(m => m.id == id); },
    
    addHistory(q) {
      const v = (q || '').toString().trim();
      if (!v) return;
      this.searchHistory = [v, ...this.searchHistory.filter(x => x !== v)].slice(0, 10);
      localStorage.setItem('search_history', JSON.stringify(this.searchHistory));
    },
    
    clearHistory() {
      this.searchHistory = [];
      localStorage.removeItem('search_history');
    },
    
    removeHistoryItem(item) {
      this.searchHistory = this.searchHistory.filter(x => x !== item);
      localStorage.setItem('search_history', JSON.stringify(this.searchHistory));
    },
    
    removeHistoryItem(item) {
      this.searchHistory = this.searchHistory.filter(x => x !== item);
      localStorage.setItem('search_history', JSON.stringify(this.searchHistory));
    }
  }
});